package com.dys.proxy3;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: 疾风
 * @ClassName: CglibProxy
 * @Description: 定义cglib的代理对象
 * @CreateDate: 2024/10/21
 * @Version: v1.0.0
 */
public class CglibProxy implements MethodInterceptor {
    /**
     * 目标对象
     */
    private final DoSomeService target;

    public CglibProxy(DoSomeService target) {
        this.target = target;
    }

    /**
     * 对外提供代理对象的方法
     * @return 目标对象
     */
    public DoSomeService createTarget() {
        // 1.创建cglib增强器
        Enhancer enhancer = new Enhancer();
        // 2.需要指定父类
        enhancer.setSuperclass(DoSomeService.class);
        // 3.代理后的回调对象
        enhancer.setCallback(this);
        return (DoSomeService) enhancer.create();
    }

    /**
     * cglib增强方法
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("------start-------");
        // String msg = target.doSomething();
        Object res = method.invoke(target, objects);
        System.out.println("------end-------");
        // return msg.toUpperCase();
        return res;
    }
}
